import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import EmployeeManage from '../components/EmployeeManage.vue'
import DepartmentManage from '../components/DepartmentManage.vue'
import LeaveManage from '../components/LeaveManage.vue'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }  // 需要登录认证
  },
  {
    path: '/employee',
    name: 'EmployeeManage',
    component: EmployeeManage,
    meta: { requiresAuth: true }  // 需要登录认证
  },
  {
    path: '/department',
    name: 'DepartmentManage',
    component: DepartmentManage,
    meta: { requiresAuth: true }  // 需要登录认证
  },
  {
    path: '/leave',
    name: 'LeaveManage',
    component: LeaveManage,
    meta: { requiresAuth: true }  // 需要登录认证
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：检查是否需要登录
router.beforeEach((to, from, next) => {
  const accessToken = localStorage.getItem('access_token')
  
  // 如果路由需要认证且没有token，跳转到登录页
  if (to.meta.requiresAuth && !accessToken) {
    next('/')
  } else if (to.path === '/' && accessToken) {
    // 如果已登录，访问登录页时跳转到首页
    next('/home')
  } else {
    next()
  }
})

export default router